package com.wyp168.leetcode;

import java.util.*;

/**
 * @ClassName ThreeSUm
 * @Description 三个数之和为0的集合
 * @Author wyp168
 * @Date 2022/7/12 11:31
 */
public class ThreeSum {
    public static void main(String[] args) {

        int[] arrInt = {0,0,0};
        System.out.println(threeSum(arrInt));


    }

    /**
     * 排序 + 双指针
     */
    public static List<List<Integer>> threeSum(int[] nums) {
        if (nums.length < 3) {
            return new ArrayList<>(new ArrayList<>());
        }

        //排序
        Arrays.sort(nums);

        if (nums[0] > 0) {
            return new ArrayList<>(new ArrayList<>());
        }
        //定义双指针
        int lIndex = -1;

        Set<List<Integer>> set = new HashSet<>(new ArrayList<>());

        while (nums[lIndex + 1] <= 0 && lIndex < nums.length - 2) {
            lIndex += 1;
            int tempLIndex = lIndex + 1;
            int rIndex = nums.length - 1;

            while (tempLIndex < rIndex) {
                int sum = nums[lIndex] + nums[tempLIndex] + nums[rIndex];
                if (sum == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[lIndex]);
                    list.add(nums[tempLIndex]);
                    list.add(nums[rIndex]);
                    set.add(list);
                    rIndex --;
                } else if(sum > 0) {
                    rIndex --;
                } else {
                    tempLIndex ++;
                }
            }
        }
        List<List<Integer>> res = new ArrayList<>(set);
        return  res;
    }
}
